package com.scenic.common.advice;

import com.scenic.common.exception.ScenicSpotException;
import com.scenic.common.bean.RespBean;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class WebExceptionHandler {
    //全局异常处理
    @ExceptionHandler(Exception.class)
    public RespBean handleRuntimeException(Exception e){
        e.printStackTrace();
        return RespBean.error("未知错误,联系管理员");
    }
    //自定义异常处理
    @ExceptionHandler(ScenicSpotException.class)
    public RespBean handleRuntimeNurisingHomeException(ScenicSpotException e){
        e.printStackTrace();
        return RespBean.error(e.getMessage());
    }
    //参数验证异常处理
    @ExceptionHandler({BindException.class})
    public RespBean handleMethodArgumentNotValidException(BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        StringBuilder sbf = new StringBuilder("校验失败 ");
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            sbf.append(fieldError.getField()).append("：").append(fieldError.getDefaultMessage()).append(", ");
        }
        String msg = sbf.toString();
        int i = msg.lastIndexOf(", ");
        msg = msg.substring(0, i);
        return RespBean.error(msg);
    }
    //runtime异常处理
    //@ExceptionHandler(RuntimeException.class)
    //public RespBean runtimeexceptionHandler(RuntimeException e) {
    //    e.printStackTrace();
    //    return RespBean.error(e.getMessage());
    //}
    @ExceptionHandler(RuntimeException.class)
    public RespBean exceptionHandler(RuntimeException e){
        e.printStackTrace();
        if (e.getCause()!= null && e.getCause().getMessage()!= null){
            return RespBean.error(e.getCause().getMessage());
        }

        return RespBean.error("未知错误，请联系管理员！！！");
    }
}
